//index.js
//获取应用实例
var app = getApp();
import Api from '../../../api/api.js';
const api = new Api();
Page({
  data: {
    userId: '',
    postId: '',
    toolList:[{"title":"添加图片","img":"/images/release/addImag.png"},{"title":"发起投票","img":"/images/release/touPiao.png"},{"title":"帮扶","img":"/images/release/bangFu.png"},{"title":"添加种草","img":"/images/release/zhongCao.png"}],
    typeList: ["晒晒", "救助", "领养", "帮扶","种草"],
    typeSelectIndex:0,
    isShowSave:false,
    textareaHide:false,
    canSave:true,
    textareaText:"",
    inputText:"",
    imageList:[],
    cityName:"添加地点",
    title:"添加标题",
    chooseTye:"video",
    videoUrl:"",
    showMedia:false,
    topIndex:0,
    zcDict:null,
    bfDict:null,
    voteDict:null,
    detailData:{},
    needToHome:true,
    textList:[],

  },
 
  onLoad: function (options) {
    wx.removeStorageSync('zcList');
    wx.removeStorageSync('bfList');
    this.data.userId = options.USER_ID;
    this.data.postId = options.POST_ID;
    this.getDetailData();

  },
  onShow(){
    var zcString = wx.getStorageSync('zcList');
    if (zcString && zcString.length > 0){
      var zcDict = JSON.parse(zcString);
      this.setData({
        bfDict:null,
        voteDict:null,
        typeSelectIndex:4,
        zcDict:zcDict
      });
    }
    var bfString = wx.getStorageSync('bfList');
    if (bfString && bfString.length > 0){
      var bfDict = JSON.parse(bfString);
      this.setData({
        zcDict:null,
        voteDict:null,
        typeSelectIndex:3,
        bfDict:bfDict
      });
    }
    if (this.data.voteDict){
      this.setData({
        zcDict:null,
        voteDict:this.data.voteDict,
        typeSelectIndex:0,
        bfDict:null
      });
    }
  },
  textareaClick(e){
    var value = e.detail.value;
    if (value > 500){
      value.substring(0,500);
    }  
    var list = value.split("#");
    this.setData({
      textareaText: value,
      inputText: value,
      textList: list
    });
    console.log(this.data.textList);
  },
  typeClick(e){
    var index = e.currentTarget.dataset.key;
    this.setData({
      typeSelectIndex:index
    })
    if (index == 0 || index == 1 || index == 2){
      wx.removeStorageSync('zcList');
      wx.removeStorageSync('bfList');
      this.setData({
        zcDict:null,
        voteDict:null,
        bfDict:null,
      });
    }
  },

  inputTextClick(){
    this.setData({
      textareaHide:false,
      textareaText:this.data.inputText

    });
  },
  toolClick(e){
    if (this.data.textareaText.length > 0){
      this.setData({
        textareaHide:true,
        inputText:this.data.textareaText
      });
    }
    var index = e.currentTarget.dataset.key;
    this.data.topIndex = index;
    if (index == 0) {
      this.goToChooseImages();
    } else if (index == 1) {
      this.goToTouPiao();
    } else if (index == 2) {
      this.goToBangFuJiDi();
    } else if (index == 3) {
      this.goToZhongCao();
    }
  },
  goToTouPiao(){
    wx.navigateTo({
      url: '/pages/release/vote/vote',
    })
  },
  goToBangFuJiDi(){
    wx.navigateTo({
      url: '/pages/index/bangfu/bangfu',
    })
  },
  goToZhongCao(){
    wx.navigateTo({
      url: '/pages/index/bfZhongCao/bfZhongCao',
    })
  },
  goToChooseImages(){
    this.chosseMedia();
  },
  saveDraft(){
    this.data.needToHome = false;
    this.savePostClick(-1);
  },
  beginSave(){
    this.data.needToHome = true;
    this.savePostClick(1);
  },
  floatClick(){
    this.setData({
      isShowSave:false
    });
  },
  saveClick(e){
    var index = parseInt(e.currentTarget.dataset.key);
    this.setData({
      isShowSave:false
    });
    if (index == 0) {
      this.savePostClick(-1);
    } else if (index == 1){
      this.goToUpPage();
    }
  },
  goToUpPage(){
      wx.navigateBack({
        complete: (res) => {},
      });
  },
  goToSelectCity(){
    wx.navigateTo({
      url: '/pages/release/selectCity/selectCity',
    })
  },
  goToAddTitle(){
    var title = this.data.title;
    if (title == '添加标题'){
      title = "";
    }
    wx.setStorageSync('post_title', title);
    wx.navigateTo({
      url: '/pages/release/title/title',
    })
  },
  savePostClick(draft){
    if (this.data.inputText.length == 0){
      app.alert("请输入正文~");
      return;
    }
    var title = this.data.title;
    if (title == "添加标题"){
      title = "";
   }
    var cityName = this.data.cityName;
    if (cityName == "添加地点"){
      cityName = "";
    }
    var type = 1;
    if (this.data.zcDict){
      type = 4;
    }
    if (this.data.voteDict){
      type = 2;
    }
    if (this.data.bfDict){
      type = 3;
    }
    if (!this.data.canSave) return;
    this.data.canSave = false;
    var _this = this;
    var map = {};
    map.address = "";
    if (this.data.bfDict){
      if (this.data.bfDict.id){
        map.baseId = this.data.bfDict.id;
      } else {
        map.baseId = this.data.bfDict.basesId;
      }
    }
    if (this.data.zcDict){
      map.productId = this.data.zcDict.productId;
      map.skuId =  this.data.zcDict.skuId;
    }
    if (this.data.voteDict){
      map.votes =  this.data.voteDict.options;
      map.voteTitle =  this.data.voteDict.title;
      map.endTime =  this.data.voteDict.endTime+"";
    }
    map.id = this.data.postId;
    map.city = cityName;
    map.content = this.data.inputText;
    map.draft = draft;
    map.endTime = "";

    map.imgs = JSON.stringify(this.data.imageList);
    map.kind = this.data.typeSelectIndex + 1;
    map.title = title;
    map.type = type;
    map.userId = this.data.userId;
    map.videoUrl = this.data.videoUrl;
    map.votes = [];

    console.log(JSON.stringify(map));
    api.getRequestData(app.postEditUrl, map, false, "POST").then(res => {
      _this.data.canSave = true;
      if (res.data.errorCode == 0) {
        if (draft == -1){
          app.showToasts("保存成功～");
        } else {
          app.showToasts("发布成功～");
        }
        setTimeout(() => {
          if (_this.data.needToHome){
            wx.navigateBack({
              complete: (res) => {;},
            })
          }
        }, timeout);
      
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }

    }).catch(err => {
      _this.data.canEvaluate = true;
    });
  },
  // 上传图片
  chosseMedia() {
    this.setData({
      showMedia:true
    });
  },
  hideShareClickView(){
    this.setData({
      showMedia:false
    });
  },
  chooseVideo(){
    this.data.chooseTye = "video";
    this.hideShareClickView();
    var _this = this;
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        console.log(res.tempFilePath)
        var path = res.tempFilePath;
         _this.upLoadimage(path);     

      }
    })
  },
  chooseImages(){
    this.data.chooseTye = "images";
    this.hideShareClickView();
    var _this = this;
    wx.chooseImage({
        count: 6,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          var tempPaths = res.tempFilePaths;
          var count = _this.data.imageList.length;
          if (count + tempPaths > 9){
            app.alert("最多上传9张图片~");
            return;
          }
          for (var i = 0;i < tempPaths.length;i++){
            var path = tempPaths[i];
            _this.upLoadimage(path);     
          }
        },
      })
  },
  upLoadimage(tempPath) {
    var _this = this;
    wx.showLoading({
      title: '上传中...',
    })

    wx.uploadFile({
      url: app.host + app.upLoadImageUrl,
      filePath: tempPath,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (response) {
        wx.hideLoading();
        if (response.statusCode == 200){
          var string = response.data;
          var dict = JSON.parse(string);
          var url = dict.model.fileFullUrl;
          console.log(url);
          if (_this.data.chooseTye == "video"){
            _this.setData({
              imageList:[],
              videoUrl:url
            });
          } else {
            _this.data.imageList.push(url)
            _this.setData({
              videoUrl:"",
              imageList:_this.data.imageList
            });
          }

        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },
  
  previewImages(e) {
    var index = parseInt(e.currentTarget.dataset.key);
    var url = this.data.imageList[index];
    wx.previewImage({
      current: url,
      urls: this.data.imageList,
    })
  },
  deleteImage(e){
    var _this = this;
    var index = parseInt(e.currentTarget.dataset.key);
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗?',
      success: function (res) {
        if (res.confirm) {
          _this.beginDelete(index);
        } else if (res.cancel) {
        }
      }
    });
  },

  beginDelete (index) {
    var _this = this;
    var list = [];
    for (var i = 0; i < _this.data.imageList.length; i++) {
      if (i != index) {
        var url = _this.data.imageList[i];
        list.push(url);
      }
    }
    _this.setData({
      imageList: list
    });
  },
  onUnload: function () {
    wx.removeStorageSync('zcList');
    wx.removeStorageSync('bfList');
  },
  getDetailData() {
    var _this = this;
    var map = {};
    map.id = this.data.postId;
    map.userId = app.USER_ID();

    api.getRequestData(app.postDetailtUrl, map, false, "GET").then(res => {
      if (res.data.errorCode == 0) {
        _this.formatData(res.data.model);
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  formatData(dataDict){
    var _this = this;
    console.log(">>>>>>>",JSON.stringify(dataDict));
    var postDict = dataDict.post;

    var kind = postDict.kind;
    if (kind == 4) {
      // 帮扶
      var bangFuDict = dataDict.bases;
      wx.setStorageSync('bfList', JSON.stringify(bangFuDict))
      _this.setData({
        zcDict:null,
        voteDict:null,
        typeSelectIndex:3,
        bfDict:bangFuDict
      });

    } else if (kind == 5) {
      // 种草
      var productId = postDict.productId;
      var skuId = postDict.skuId;
      _this.getGoodDetail(productId,skuId);
    } else {
      var voteList = dataDict.votes;
      if (voteList){
        var voteDict = {};
        voteDict.title = postDict.voteTitle;
        var endTime = postDict.endTime;
        voteDict.endDate = endTime;
        var optionsList = [];
        for(var i = 0;i < voteList.length;i++){
          var dict = voteList[i];
          optionsList.push(dict.vote.content);
        }
        voteDict.options = optionsList;
        _this.setData({
          voteDict:voteDict
        });
        console.log("=======",_this.data.voteDict);

      }
    }
    var imgString = postDict.imgs;
    if (imgString){
      if (imgString.length > 0){
        var list = JSON.parse(imgString);
        console.log("list====",list);
        _this.setData({
          imageList:list
        });
      }
    }
    var videoUrl = postDict.videoUrl;
    if (videoUrl){
      if (videoUrl.length > 0){
        _this.setData({
          videoUrl:videoUrl
        });
      }
    }
    var content = postDict.content;
    if (content){
      var list = content.split("#");
      this.setData({
        textList: list
      });
    }
    _this.setData({
      title:postDict.title.length > 0 ?postDict.title:'添加标题',
      cityName:postDict.city.length > 0 ? postDict.city:'添加地点',
      textareaText:postDict.content,
      inputText:postDict.content,
      detailData: dataDict
    });
  },
  getGoodDetail(productId,skuId) {
    var _this = this;
    var map = {};
    map.productId = productId;
    api.getRequestData(app.goodsDetailUrl, map, true, "GET").then(res => {
      if (res.data.errorCode == 0) {
        var list = res.data.model.skus;
        var skuDict = null;
        for(var i = 0;i < list.length;i++){
          var dict = list[i];
          if (dict.id == skuId){
            skuDict = dict;
            break;
          }
        }
       _this.setData({
        bfDict:null,
        voteDict:null,
        typeSelectIndex:4,
        zcDict: skuDict
       });
      } 
    });
  },
})
